﻿using AbpIntegrationDemo.Api.Domains.OrderLogs;
using AbpIntegrationDemo.Api.Domains.Orders;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;

namespace AbpIntegrationDemo.Api.Applications.Orders.DataLoaders;

public class OrderLogBatchDataLoader : BatchDataLoader<Guid, OrderLog>, IScopedDependency
{
    private readonly IRepository<OrderLog, Guid> _orderLogRepository;
    private readonly IRepository<Order, Guid> _orderRepository;

    public OrderLogBatchDataLoader(
        IRepository<OrderLog, Guid> orderLogRepository,
        IRepository<Order, Guid> prderRepository,
        IBatchScheduler batchScheduler,
        DataLoaderOptions? options = null)
        : base(batchScheduler, options)
    {
        _orderLogRepository = orderLogRepository;
        _orderRepository = prderRepository;
    }

    protected override async Task<IReadOnlyDictionary<Guid, OrderLog>> LoadBatchAsync(
        IReadOnlyList<Guid> keys,
        CancellationToken cancellationToken)
    {
        var test = await _orderRepository.GetQueryableAsync();
        var orders = await test.ToListAsync();

        var queryable = await _orderLogRepository.GetQueryableAsync();
        var orderLogs = await queryable.Where(q => keys.Contains(q.OrderId)).ToListAsync();
        return orderLogs.GroupBy(x => x.OrderId).ToDictionary(x => x.Key, x => x.FirstOrDefault());
    }
}
